<?php
namespace app\product\model;

use think\Model;
use think\Db;
use app\product\model\Supplier as SupplierModel;

class Product extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    public function getSupplierTextAttr($value)
    {
        $name = SupplierModel::where('id', $value)->value('name');
        return $name;
    }

    public function getWarehousingAttr($value,$data)
    {
        $num = Db::name('stock')->where('product_id',$data['id'])
                                ->where('type','入库')
                                ->where('shop_id',session('shop_id'))
                                ->where('status',1)
                                ->sum('product_num');
        return $num;
    }
    public function getOutOfAttr($value,$data)
    {
        $num = Db::name('stock')->where('product_id',$data['id'])
                                ->where('type','出库')
                                ->where('shop_id',session('shop_id'))
                                ->where('status',1)
                                ->sum('product_num');
        return $num;
    }
    public function getUnitTextAttr($value)
    {
        $name = Db::name('unit')->where('id',$value)->value('name');
        return $name;
    }
    public function getDecompositionTextAttr($value)
    {
        $name = Db::name('unit')->where('id',$value)->value('name');
        return $name;
    }
    public function hasCategory()
    {
        return $this->hasOne('Category', 'id', 'category_id');
    }
    public function hasBrand()
    {
        return $this->hasOne('Brand', 'id', 'brand_id');
    }
    public function hasSupplier()
    {
        return $this->hasOne('Supplier', 'id', 'supplier_id');
    }
    public function hasUnit()
    {
        return $this->hasOne('Unit', 'id', 'unit_id');
    }

    /**
     * 将数据集格式化成下拉选项
     * @param int $id 选中的ID
     * @author 橘子俊 <364666827@qq.com>
     * @return string
     */
    public static function getSelect($data = [], $id = 0, $level = 0)
    {
        if (empty($data)) {
            return '';
        }
        $str = $separ = '';
        if ($level > 0) {
            for ($i=0; $i < $level; $i++) {
                $separ .= '&nbsp;&nbsp;&nbsp;';
            }
            $separ .= '┣&nbsp;';
        }

        foreach ($data as $k => $v) {
            if ($id == $v['id']) {
                $str .= '<option value="'.$v['id'].'" selected>'.$separ.$v['name'].'</option>';
            } else {
                $str .= '<option value="'.$v['id'].'">'.$separ.$v['name'].'</option>';
            }
            if (isset($v['childs'])) {
                $str.= self::getSelect($v['childs'], $id, $level+1);
            }
        }
        return $str;
    }

}
